{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# %load E:\\Users\\ASUS\\PycharmProjects\\CV2\\otsu.py\n",
    "import cv2 as cv\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "filename = r'E:\\data\\rice.png'\n",
    "img = cv.imread(filename)\n",
    "#计算直方图\n",
    "hist=cv.calcHist([img],[0],None,[256],[0,255])\n",
    "#S画直方图\n",
    "plt.figure()\n",
    "plt.title(\"Grayscale Histogram\")\n",
    "plt.xlabel(\"Bins\")\n",
    "plt.ylabel(\"number of Pixels\")\n",
    "plt.plot(hist)\n",
    "plt.xlim([0,256])\n",
    "plt.show()\n",
    "cv.waitKey()\n",
    "cv.destroyAllWindows()\n",
    "\n",
    "# 大津算法分割图像\n",
    "imgMedian=cv.medianBlur(img,5)\n",
    "imgGray=cv.cvtColor(imgMedian,cv.COLOR_BGR2GRAY)\n",
    "retval,imgThreshold1=cv.threshold(imgGray,120,255,cv.THRESH_BINARY)\n",
    "#retval,imgThreshold2=cv.threshold(imgGray,120,255,cv.THRESH_BINARY_INV)\n",
    "#retval,imgThreshold3=cv.threshold(imgGray,120,255,cv.THRESH_TRUNC)\n",
    "#retval,imgThreshold4=cv.threshold(imgGray,120,255,cv.THRESH_TOZERO)\n",
    "#retval,imgThreshold5=cv.threshold(imgGray,120,255,cv.THRESH_TOZERO_INV)\n",
    "cv.imshow(\"Source image\",img)\n",
    "cv.imshow(\"Threshold image1\",imgThreshold1)\n",
    "#cv.imshow(\"Threshold image2\",imgThreshold2)\n",
    "#cv.imshow(\"Threshold image3\",imgThreshold3)\n",
    "#cv.imshow(\"Threshold image4\",imgThreshold4)\n",
    "#cv.imshow(\"Threshold image5\",imgThreshold5)\n",
    "cv.waitKey()\n",
    "cv.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
